<script lang="ts" setup>
import { ref, watch } from 'vue'
import { getOssInfo } from '@/api/user'
import { useUserStore } from '@/store/user'

interface Props {
  modelValue?: string | any[]
  uploadText?: string
  uploadHint?: string
  iconType?: any
}

interface Emits {
  (e: 'update:modelValue', value: string | any[]): void
  (e: 'success', file: any): void
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: () => [],
  uploadText: '上传图片',
  uploadHint: '点击上传图片',
  iconType: 'camera-filled',
})

const emit = defineEmits<Emits>()
const userStore = useUserStore()

// 处理modelValue，确保始终是数组格式
function normalizeModelValue(value: string | any[]) {
  if (typeof value === 'string') {
    return value ? value.split(',') : []
  }
  return Array.isArray(value) ? value : []
}

const fileList = ref(normalizeModelValue(props.modelValue))
const uploading = ref(false)
const uploadProgress = ref(0)

// 监听外部传入的值变化
watch(() => props.modelValue, (newVal) => {
  fileList.value = normalizeModelValue(newVal)
}, { deep: true })

// 选择图片
function chooseImage(replaceIndex?: number) {
  if (uploading.value)
    return

  uni.chooseImage({
    count: 1,
    sizeType: ['compressed'],
    sourceType: ['album', 'camera'],
    success: (res) => {
      const tempFilePath = res.tempFilePaths[0]
      uploadImage(tempFilePath, replaceIndex)
    },
    fail: (err) => {
      console.error('选择图片失败:', err)
      uni.showToast({
        title: '选择图片失败',
        icon: 'none',
      })
    },
  })
}

// 上传图片到OSS
async function uploadImage(filePath: string, replaceIndex?: number) {
  try {
    uploading.value = true
    uploadProgress.value = 0

    // 获取OSS配置信息
    const ossInfo = await getOssInfo()
    const { host, dir, filename, policy, accessId, signature } = ossInfo

    // 构建上传参数
    const formData = {
      key: dir + filename,
      policy,
      OSSAccessKeyId: accessId,
      signature,
    }
    // 获取用户token
    const token = userStore.userInfo.token
    const headers = {
      Authorization: token ? `Bearer ${token}` : '',
    }
    // 上传文件
    const uploadTask = uni.uploadFile({
      url: host,
      filePath,
      name: 'file',
      formData,
      header: headers,
      success: (uploadRes) => {
        if (uploadRes.statusCode === 204 || uploadRes.statusCode === 200) {
          // 上传成功
          const fileUrl = `${host}/${formData.key}`

          // 根据是否有replaceIndex决定是替换还是新增
          if (typeof replaceIndex === 'number' && replaceIndex >= 0) {
            // 替换指定位置的图片
            fileList.value[replaceIndex] = fileUrl
          }
          else {
            // 新增图片
            fileList.value.push(fileUrl)
          }

          const newList = Array.isArray(props.modelValue) ? fileList.value : fileList.value.join(',')
          emit('update:modelValue', newList)
          emit('success', newList)
          uni.showToast({
            title: '上传成功',
            icon: 'success',
          })
        }
        else {
          throw new Error('上传失败')
        }
      },
      fail: (err) => {
        console.error('上传失败:', err)
        uni.showToast({
          title: '上传失败',
          icon: 'none',
        })
      },
      complete: () => {
        uploading.value = false
        uploadProgress.value = 0
      },
    })

    // 监听上传进度
    uploadTask.onProgressUpdate((res) => {
      uploadProgress.value = res.progress
    })
  }
  catch (error) {
    console.error('上传图片失败:', error)
    uploading.value = false
    uploadProgress.value = 0
    uni.showToast({
      title: '上传失败',
      icon: 'none',
    })
  }
}

// 删除图片
function removeImage(index?: number) {
  if (typeof index === 'number') {
    // 删除指定位置的图片
    fileList.value.splice(index, 1)
  }
  else {
    // 删除所有图片（保持向后兼容）
    fileList.value = []
  }
  const newList = Array.isArray(props.modelValue) ? fileList.value : fileList.value.join(',')
  emit('update:modelValue', newList)
}

// 预览图片
function previewImage(index?: number) {
  if (fileList.value.length > 0) {
    const currentIndex = typeof index === 'number' ? index : 0
    const imageUrl = fileList.value[currentIndex]
    if (imageUrl) {
      uni.previewImage({
        current: currentIndex,
        urls: fileList.value,
      })
    }
  }
}
</script>

<template>
  <view class="image-upload" style="width: 100%;">
    <!-- 图片列表显示 -->
    <view v-if="fileList.length > 0" class="image-list">
      <view
        v-for="(image, index) in fileList"
        :key="index"
        class="image-item"
      >
        <view class="image-preview">
          <image
            :src="image"
            class="preview-image"
            mode="aspectFill"
            @click.stop="previewImage(index)"
          />
          <view class="image-mask">
            <view class="mask-content">
              <view class="mask-item" @click.stop="previewImage(index)">
                <uni-icons type="eye" size="20" color="#fff" />
                <text class="mask-text">查看</text>
              </view>
              <view class="mask-item" @click.stop="chooseImage(index)">
                <uni-icons type="camera-filled" size="20" color="#fff" />
                <text class="mask-text">重新上传</text>
              </view>
            </view>
          </view>
          <view class="delete-btn" @click.stop="removeImage(index)">
            <uni-icons type="close" size="16" color="#fff" />
          </view>
        </view>
      </view>
    </view>

    <!-- 上传占位符 -->
    <view v-if="fileList.length === 0" class="upload-container" @click="chooseImage()">
      <view class="upload-placeholder">
        <view class="upload-icon">
          <uni-icons :type="iconType" size="28" color="#FF770D" />
        </view>
        <view class="upload-text">
          {{ uploadText }}
        </view>
        <view class="upload-hint">
          {{ uploadHint }}
        </view>
      </view>
    </view>

    <!-- 上传进度 -->
    <view v-if="uploading" class="upload-progress">
      <view class="progress-bar">
        <view class="progress-fill" :style="{ width: `${uploadProgress}%` }" />
      </view>
      <text class="progress-text">上传中 {{ uploadProgress }}%</text>
    </view>
  </view>
</template>

<style lang="scss" scoped>
.image-upload {
  width: 100%;
}

.upload-container {
  width: 100%;
  position: relative;
}

.upload-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 140px;
  border: 2px dashed #ff770d;
  border-radius: 16px;
  background: linear-gradient(135deg, #fff8f0 0%, #fff5eb 100%);
  position: relative;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  cursor: pointer;

  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: linear-gradient(135deg, rgba(255, 119, 13, 0.05) 0%, rgba(255, 119, 13, 0.02) 100%);
    border-radius: 14px;
    opacity: 0;
    transition: opacity 0.3s ease;
  }

  &:hover {
    border-color: #e6690b;
    transform: translateY(-3px);
    box-shadow: 0 8px 25px rgba(255, 119, 13, 0.15);

    &::before {
      opacity: 1;
    }

    .upload-icon {
      transform: scale(1.1);
      background-color: rgba(255, 119, 13, 0.15);
    }
  }

  &:active {
    transform: translateY(-1px);
  }
}

.upload-icon {
  margin-bottom: 10px;
  padding: 14px;
  background-color: rgba(255, 119, 13, 0.1);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  box-shadow: 0 2px 8px rgba(255, 119, 13, 0.1);
}

.upload-text {
  font-size: 15px;
  color: #ff770d;
  font-weight: 600;
  margin-bottom: 6px;
  text-align: center;
  letter-spacing: 0.5px;
}

.upload-hint {
  font-size: 11px;
  color: #999;
  text-align: center;
  line-height: 1.4;
  opacity: 0.8;
}

.image-list {
  display: flex;
  flex-wrap: wrap;
  gap: 20rpx;
}

.image-item {
  width: 100%;
  height: 200rpx;
  position: relative;
}

.image-preview {
  width: 100%;
  height: 100%;
  border-radius: 12rpx;
  overflow: hidden;
  position: relative;
}

.preview-image {
  width: 100%;
  height: 100%;
  border-radius: 16px;
}

.image-mask {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 1;
  transition: opacity 0.3s ease;
  border-radius: 16px;
}

.image-preview:hover .image-mask {
  opacity: 1;
}

.mask-content {
  display: flex;
  align-items: center;
  gap: 20px;
}

.mask-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 4px;
  width: 60px;
  height: 60px;
  border-radius: 8px;
  background: rgba(255, 255, 255, 0.1);
  transition: all 0.3s ease;
  cursor: pointer;

  &:hover {
    background: rgba(255, 255, 255, 0.2);
    transform: scale(1.05);
  }

  &:active {
    transform: scale(0.95);
  }
}

.mask-text {
  color: #fff;
  font-size: 12px;
  white-space: nowrap;
}

.delete-btn {
  position: absolute;
  top: 8px;
  right: 8px;
  width: 24px;
  height: 24px;
  background: rgba(0, 0, 0, 0.6);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 10;
}

.upload-progress {
  margin-top: 12px;
  width: 100%;
}

.progress-bar {
  width: 100%;
  height: 4px;
  background: #f0f0f0;
  border-radius: 2px;
  overflow: hidden;
  margin-bottom: 6px;
}

.progress-fill {
  height: 100%;
  background: #ff770d;
  border-radius: 2px;
  transition: width 0.3s ease;
}

.progress-text {
  font-size: 12px;
  color: #666;
  text-align: center;
  display: block;
  width: 100%;
}
</style>
